<?php
class series_model extends CI_Model{
	
	function __construct(){
		parent::__construct();
		$this->load->database();
	}
	
	/**
	 * Inserta a la bd una serie nueva con los parametros que llegen
	 */
	public function addSerie($params){
		$this->load->model('user_model');
		$res = $this->user_model->getIdUserToken($params);
		//informacion del usuario
		$data_usr = $res->row_array();
		
		$values = array(
			'id_usuario' 	=> $data_usr['id_usuario'],
			'titulo' 		=> $params['title'],
			'titulo_limpio' => Sys::toAscii($params['title']),
			'fecha_estreno' => $params['date_release']
		);
		if(isset($params['sinopsis_spa']))
			$values['sinopsis_spa'] = $params['sinopsis_spa'];
		if(isset($params['sinopsis_eng']))
			$values['sinopsis_eng'] = $params['sinopsis_eng'];
		
		$this->db->insert('series', $values);
		$id_serie = $this->db->insert_id();
		
		//actores de la serie
		$this->insertCast($params, $id_serie);
		
		//categorias de la serie
		$this->insertCategories($params, $id_serie);
		
		return array('id_serie' => $id_serie);
	}
	
	/**
	 * Actualiza en la bd una serie con los parametros que llegen
	 */
	public function updateSerie($params){
		$values = array(
			'titulo' 		=> $params['title'],
			'fecha_estreno' => $params['date_release']
		);
		if(isset($params['sinopsis_spa']))
			$values['sinopsis_spa'] = $params['sinopsis_spa'];
		if(isset($params['sinopsis_eng']))
			$values['sinopsis_eng'] = $params['sinopsis_eng'];
		
		$this->db->update('series', $values, 'id_serie = '.$params['serie']);
		
		//actores de la serie
		$this->db->delete('series_reparto', 'id_serie = '.$params['serie']);
		$this->insertCast($params, $params['serie']);
		
		//categorias de la serie
		$this->db->delete('series_categorias', 'id_serie = '.$params['serie']);
		$this->insertCategories($params, $params['serie']);
		
		return array('id_serie' => $params['serie']);
	}
	
	
	/**
	 * Inserta a la bd los actores que pertenecen a una serie
	 */
	private function insertCast($params, $id_serie){
		if(isset($params['cast'])){
			if(count($params['cast']) > 0){
				$values = array();
				foreach ($params['cast'] as $key => $itm) {
					$values[] = array(	
						'id_actor' => $itm,
						'id_serie' => $id_serie
					);
				}
				$this->db->insert_batch('series_reparto', $values);
			}
		}
	}
	
	/**
	 * Inserta a la bd las categorias que pertenecen a una serie
	 */
	private function insertCategories($params, $id_serie){
		if(isset($params['categories'])){
			if(count($params['categories']) > 0){
				$values = array();
				foreach ($params['categories'] as $key => $itm) {
					$values[] = array(	
						'id_categoria' 	=> $itm,
						'id_serie' 		=> $id_serie
					);
				}
				$this->db->insert_batch('series_categorias', $values);
			}
		}
	}


	/**
	 * Agregar una temporada a una serie
	 */
	public function addSeason($params){
		if($this->exist('series', array('id_serie' => $params['serie']))){
			$this->load->model('user_model');
			$res = $this->user_model->getIdUserToken($params);
			//informacion del usuario
			$data_usr = $res->row_array();
			
			$this->load->library('imageshack');
			//$this->load->library('UploadFiles');
			
			$is_file 	= FALSE;
			$image		= FALSE;
			
			if(isset($_FILES['poster']['name'])){
				if(!empty($_FILES['poster']['name'])){
					$image = $this->imageshack->upload(
						array(
							'file' 		=> 'poster',
							'img_temp' 	=> TRUE,
							'size' 		=> array('big','medium','small')
						));
					// $image = $this->uploadfiles->uploadFile(array(
							// 'file' 		=> 'poster',
							// 'img_temp' 	=> TRUE,
							// 'size' 		=> array('big','medium','small')
						// ));
					$is_file = TRUE;
				}
			}
			
			if(!$is_file){
				if(isset($params['poster'])){
					if(!empty($params['poster'])){
						$image = $this->imageshack->upload(
							array(
								'file' 		=> $params['poster'],
								'img_temp' 	=> FALSE,
								'size' 		=> array('big','medium','small')
							));
						// $image = $this->uploadfiles->uploadFile(array(
								// 'file' 		=> $params['poster'],
								// 'img_temp' 	=> FALSE,
								// 'size' 		=> array('big','medium','small')
							// ));
					}
				}
			}
			
			if($image != FALSE){
				$values = array(
					'id_usuario' 		=> $data_usr['id_usuario'],
					'id_serie'			=> $params['serie'],
					'no_temporada' 		=> $params['no_season'],
					'fecha_estreno' 	=> $params['date_release'],
					'url_poster_big' 	=> $this->imageshack->getInfo('image_link', 'big'), //$image['big']['url']
					'url_poster_medium' => $this->imageshack->getInfo('image_link', 'medium'), //$image['medium']['url']
					'url_poster_small' 	=> $this->imageshack->getInfo('image_link', 'small'), //$image['small']['url']
				);
				if(isset($params['trailers']))
					$values['trailer'] = $params['trailers'];
				if(isset($params['coming_soon']))
					$values['prox_estreno'] = $params['coming_soon'];
				
				$this->db->insert('series_temporadas', $values);
				$id_season = $this->db->insert_id();
				
				return array(
					'id_serie' => $params['serie'],
					'id_season' => $id_season
				);
			}
			return 2;
		}
		return 1;
	}

	/**
	 * Modificar una temporada de una serie
	 */
	public function updateSeason($params){
		if($this->exist('series', array('id_serie' => $params['serie']))){
			if($this->exist('series_temporadas', array('id_temporada' => $params['season']))){
				$values = array(
					'id_serie' => $params['serie']
				);
				
				$image = FALSE;
				if(isset($_FILES['poster']['name']) || isset($params['poster'])){
					$this->load->library('imageshack');
					//$this->load->library('UploadFiles');
					if(isset($_FILES['poster']['name'])){
						if(!empty($_FILES['poster']['name'])){
							$image = $this->imageshack->upload(
								array(
									'file' 		=> 'poster',
									'img_temp' 	=> TRUE,
									'size' 		=> array('big','medium','small')
								));
							//$image = $this->uploadfiles->uploadFile();
						}
					}
					
					if($image == FALSE){
						if(isset($params['poster'])){
							if(!empty($params['poster'])){
								$image = $this->imageshack->upload(
									array(
										'file' 		=> $params['poster'],
										'img_temp' 	=> FALSE,
										'size' 		=> array('big','medium','small')
									));
								//$image = $this->uploadfiles->uploadFile();
							}
						}
					}
					
					if($image != FALSE){
						$values['url_poster_big'] 		= $this->imageshack->getInfo('image_link', 'big'); //$image['big']['url']
						$values['url_poster_medium'] 	= $this->imageshack->getInfo('image_link', 'medium'); //$image['medium']['url']
						$values['url_poster_small'] 	= $this->imageshack->getInfo('image_link', 'small'); //$image['small']['url']
					}
				}
				
				if(isset($params['no_season']))
					$values['no_temporada'] = $params['no_season'];
				if(isset($params['date_release']))
					$values['fecha_estreno'] = $params['date_release'];
				if(isset($params['trailers']))
					$values['trailer'] = $params['trailers'];
				if(isset($params['coming_soon']))
					$values['prox_estreno'] = $params['coming_soon'];
				
				$this->db->update('series_temporadas', $values, 'id_temporada = '.$params['season']);
				
				return array(
					'id_serie' => $params['serie'],
					'id_season' => $params['season']
				);
			}
			return 2; //no existe la temporada
		}
		return 1; //no existe la serie
	}

	/**
	 * Obtiene la informacion de una temporada
	 */
	public function getSeason($params){
		if($this->exist('series_temporadas', array('id_temporada' => $params['season']))){
			$res_season = $this->db
				->query("
				SELECT 
					s.id_serie, 
					s.titulo AS title_serie, 
					s.titulo_limpio AS clean_title, 
					st.id_temporada AS id_season, 
					st.no_temporada AS no_season, 
					st.url_poster_big, 
					s.sinopsis_spa AS synopsis_spa,
					s.sinopsis_eng AS synopsis_eng,
					st.trailer,
					st.prox_estreno AS coming_soon,
					Date(st.fecha_estreno) AS date_release,
					get_rank(st.id_temporada, 's') AS ranking,
					get_votes(st.id_temporada, 's') AS votes,
					(SELECT 'Serie') AS type,
					u.nombre AS posted_by
				FROM  `series` AS s
					INNER JOIN  `series_temporadas` AS st ON  `s`.`id_serie` =  `st`.`id_serie` 
					INNER JOIN  `usuarios` AS u ON  `u`.`id_usuarios` =  `st`.`id_usuario`
				WHERE  `st`.`id_temporada` = ".$params['season']."
				");
			$date_season = $res_season->row_array();
			
			//obtenemos las categorias de la serie
			$date_season['categories'] = $this->getCategories($date_season['id_serie']);
			
			//obtenemos los actores de una serie
			$date_season['cast'] = $this->getCast($date_season['id_serie']);
			
			//obtenemos el listado de temporadas
			$date_season['seasons'] = $this->getListSeasons($date_season['id_serie'], $params['season']);
			
			//obtenemos el listado de capitulos de la temporada activa
			$date_season['episodes'] = $this->getListEpisodes($params['season']);
			
			return $date_season;
		}
		return 1;
	}
	
	
	/**
	 * Obtiene el listado de temporadas
	 */
	private function getListSeasons($id_serie, $id_season){
		$res_lsit = $this->db
			->select("id_temporada AS id, no_temporada AS no_season, (SELECT 0) AS active")
			->from('series_temporadas')
			->where('id_serie = '.$id_serie)
			->order_by('no_temporada', 'ASC')
		->get();
		$list = array();
		foreach ($res_lsit->result_array() as $value) {
			if($id_season == $value['id'])
				$value['active'] = '1';
			$list[] = $value;
		}
		return $list;
	}
	
	/**
	 * Obtiene el listado de capitulos de la temporada activa
	 */
	private function getListEpisodes($id_season){
		$res_lsit = $this->db
			->select("
				id_capitulo AS id, 
				no_capitulo AS no_episode, 
				titulo AS title, 
				titulo_limpio AS clean_title,
				fecha_estreno AS release_date,
				status")
			->from('series_capitulos')
			->where('id_temporada = '.$id_season)
			->order_by('no_capitulo', 'ASC')
		->get();
		$list = array();
		foreach ($res_lsit->result_array() as $value) {
			$list[] = $value;
		}
		return $list;
	}

	
	
	/**
	 * Agrega un capitulo a una serie
	 */
	public function addEpisode($params){
		if($this->exist('series_temporadas', array('id_temporada' => $params['season']))){
			$this->load->model('user_model');
			$res = $this->user_model->getIdUserToken($params);
			//informacion del usuario
			$data_usr = $res->row_array();
			
			$values = array(
				'id_usuario' 		=> $data_usr['id_usuario'],
				'id_temporada'		=> $params['season'],
				'no_capitulo' 		=> $params['no_episode'],
				'titulo' 			=> $params['title'],
				'titulo_limpio' 	=> Sys::toAscii($params['title']),
				'fecha_add'			=> date("Y-m-d")
			);
			// if(isset($params['format_episode']))
				// $values['formato'] = $params['format_episode'];
			// if(isset($params['quality']))
				// $values['calidad'] = $params['quality'];
			// if(isset($params['duration']))
				// $values['duracion'] = $params['duration'];
			// if(isset($params['size']))
				// $values['tamanio'] = $params['size'];
			// if(isset($params['languaje']))
				// $values['idioma'] = $params['languaje'];
			// if(isset($params['subtitles']))
				// $values['subtitulos'] = $params['subtitles'];
			if(isset($params['sinopsis_spa']))
				$values['sinopsis_spa'] = $params['sinopsis_spa'];
			if(isset($params['sinopsis_eng']))
				$values['sinopsis_eng'] = $params['sinopsis_eng'];
			if(isset($params['date_release']))
				$values['fecha_estreno'] = $params['date_release'];
			
			$this->db->insert('series_capitulos', $values);
			$id_episode = $this->db->insert_id();
			
			// $this->addScreenShot($params, $id_episode);
// 			
			// $this->addSourcesServers($params, $id_episode);
			
			if(isset($params['on_fb']))
				if($params['on_fb']==1){
					$this->load->library('my_facebook');
					$this->my_facebook->_makePost('series',$id_episode);
				}
			
			return array(
				'id_season' => $params['season'],
				'id_episode' => $id_episode
			);
		}
		return 1;
	}
	
	/**
	 * Modifica la informacion de un capitulo de una serie
	 */
	public function updateEpisode($params){
		if($this->exist('series_temporadas', array('id_temporada' => $params['season']))){
			$inf_episode = $this->exist('series_capitulos', array('id_capitulo' => $params['episode']), TRUE);
			if(is_object($inf_episode)){
				$values = array(
					'id_temporada'	=> $params['season'],
					'fecha'			=> date("Y-m-d H:i:s"),
					'status'		=> 1
				);
				if(isset($params['no_episode'])) 		$values['no_capitulo'] 	= $params['no_episode'];
				if(isset($params['title'])) 			$values['titulo'] 		= $params['title'];
				if($inf_episode->status == '0'){
					$values['fecha_add']	= $values['fecha'];
					$values['titulo_limpio']= Sys::toAscii($params['title']);
				}
				// if(isset($params['format_episode'])) 	$values['formato'] 		= $params['format_episode'];
				// if(isset($params['quality'])) 			$values['calidad'] 		= $params['quality'];
				// if(isset($params['duration'])) 			$values['duracion'] 	= $params['duration'];
				// if(isset($params['size'])) 				$values['tamanio'] 		= $params['size'];
				// if(isset($params['languaje'])) 			$values['idioma'] 		= $params['languaje'];
				// if(isset($params['subtitles'])) 		$values['subtitulos'] 	= $params['subtitles'];
				if(isset($params['sinopsis_spa'])) 		$values['sinopsis_spa'] = $params['sinopsis_spa'];
				if(isset($params['sinopsis_eng'])) 		$values['sinopsis_eng'] = $params['sinopsis_eng'];
				if(isset($params['date_release'])) 		$values['fecha_estreno'] = $params['date_release'];
				
				$this->db->update('series_capitulos', $values, 'id_capitulo = '.$params['episode']);
				
				// $this->addScreenShot($params, $params['episode'], TRUE);
				
				$this->db->delete('series_capitulos_fuentes', array('id_capitulo' => $params['episode']));
				$this->addSourcesServers($params, $params['episode']);
				
				if(isset($params['on_fb']))
					if($params['on_fb']==1){
						$this->load->library('my_facebook');
						$this->my_facebook->_makePost('series',$params['episode']);
					}
				
				return array(
					'id_season' => $params['season'],
					'id_episode' => $params['episode']
				);
			}
			return 2;
		}
		return 1;
	}

	/**
	 * Obtiene la informacion de un capitulo de una serie
	 */
	public function getEpisode($params){
		if($this->exist('series_capitulos', array('id_capitulo' => $params['episode']))){
			$res_episode = $this->db
				->query("
				SELECT 
					s.id_serie, 
					s.titulo AS title_serie, 
					s.titulo_limpio AS clean_title_serie, 
					st.id_temporada AS id_season, 
					st.no_temporada AS no_season, 
					st.url_poster_big, 
					st.trailer,
					Date(st.fecha_estreno) AS date_release,
					(SELECT 'Serie') AS type, 
					sc.id_capitulo AS id_episode, 
					sc.no_capitulo AS no_episode, 
					sc.titulo AS title_episode, 
					sc.titulo_limpio AS clean_title_episode, 
					sc.sinopsis_spa AS synopsis_spa, 
					sc.sinopsis_eng AS synopsis_eng, 
					Date(sc.fecha) AS last_update, 
					Date(sc.fecha_add) AS date,
					sc.ranking,
					get_votes(sc.id_capitulo, 'e') AS votes,
					sc.id_facebook,
					sc.fecha_estreno AS date_release_episode,
					sc.status AS status,
					u.nombre AS posted_by
				FROM (`series` AS s) 
					INNER JOIN `series_temporadas` AS st ON `s`.`id_serie` = `st`.`id_serie` 
					INNER JOIN `series_capitulos` AS sc ON `st`.`id_temporada` = `sc`.`id_temporada` 
					INNER JOIN `usuarios` AS u ON `u`.`id_usuarios` = `sc`.`id_usuario` 
				WHERE `sc`.`id_capitulo` = ".$params['episode']."
				");
			$date_episode = $res_episode->row_array();
			
			//obtenemos los screenshots del capitulo
			$res_screen = $this->db
				->select('url_captura AS url_screen, primaria AS ´primary´')
				->from('series_capitulos_capturas')
				->where('id_capitulo = '.$params['episode'])
				->order_by('primaria', 'DESC')
			->get();
			$date_episode['screenshots'] = array();
			foreach ($res_screen->result_array() as $value) {
				$value['primary'] = $value['´primary´'];
				unset($value['´primary´']);
				$date_episode['screenshots'][] = $value;
			}

			//obtenemos las categorias de la serie
			$date_episode['categories'] = $this->getCategories($date_episode['id_serie'], 0);
			
			//obtenemos los actores de una serie
			$date_episode['cast'] = $this->getCast($date_episode['id_serie']);
			
			//obtenemos las fuentes del capitulo
			$res_sourse = $this->db->query('SELECT 
					scf.id_chash AS id_source,
					s.id_servidor AS id, 
					s.nombre AS name, 
					s.url_img,
					s.online AS online1,
					s.online_pelim,
					scf.online, 
					scf.fuente AS short,
					scf.fuente_origen AS origen,
					IFNULL(scf.idioma, "") AS language,
					IFNULL(scf.subtitulos, "") AS subtitle,
					IFNULL(scf.formato, "") AS format_film,
					IFNULL((SELECT nombre FROM categorias WHERE id_categoria = scf.calidad), "") AS quality,
					IFNULL(scf.duracion, "") AS duration,
					IFNULL(scf.tamanio, "") AS size,
					IFNULL(scf.url_subtitulos, "") AS url_subtitle,
					IFNULL(sfv.positivo, 0) AS votes_pos,
					IFNULL(sfv.negativo, 0) AS votes_neg,
					IFNULL(IF(usu.usuario="",usu.nombre,usu.usuario),"") AS user
				FROM servidores AS s
					INNER JOIN series_capitulos_fuentes AS scf ON s.id_servidor = scf.id_servidor
					LEFT JOIN usuarios AS usu ON usu.id_usuarios = scf.id_usuario
					LEFT JOIN (
							SELECT `id_chash`, Sum(positivo) AS positivo, Sum(negativo) AS negativo FROM `series_capitulos_fuentes_votos` GROUP BY id_chash
					) as sfv ON sfv.id_chash = scf.id_chash
				WHERE scf.id_capitulo = '.$params['episode'].'
				ORDER BY s.nombre ASC');
			$date_episode['sources'] = array();
			foreach ($res_sourse->result_array() as $value) {
				$date_episode['sources'][] = $value;
			}
			
			return $date_episode;
		}
		return 1;
	}

	
	/**
	 * Obtiene los actores de una serie
	 */
	public function getCast($id_serie){
		$res_cast = $this->db
			->select('a.id_actor AS id, a.nombre AS name')
			->from('actores AS a')
				->join('series_reparto AS sr', 'a.id_actor = sr.id_actor', 'inner')
			->where('sr.id_serie = '.$id_serie)
			->order_by('a.nombre', 'ASC')
		->get();
		//$res_cast = $this->db->get();
		$cast = array();
		foreach ($res_cast->result_array() as $value) {
			$cast[] = $value;
		}
		return $cast;
	}
	
	/**
	 * Obtiene las categorias de una serie
	 */
	public function getCategories($id_serie, $calidad=null){
		if($calidad==1) //solo categorias de tipo Calidad o ripeo
			$ssql = 'c.calidad = 1 AND ';
		elseif($calidad==0)
			$ssql = 'c.calidad = 0 AND ';
		
		$res_cate = $this->db
			->select('c.id_categoria AS id, c.nombre AS name')
			->from('categorias AS c')
				->join('series_categorias AS sc', 'c.id_categoria = sc.id_categoria', 'inner')
			->where($ssql.'sc.id_serie = '.$id_serie)
			->order_by('c.nombre', 'ASC')
		->get();
		$categories = array();
		foreach ($res_cate->result_array() as $value) {
			$categories[] = $value;
		}
		return $categories;
	}
	
	/**
	 * Agrega capturas de pantalla a los capitulos de uan serie.
	 * El ultimo agregado se combierte en la principal
	 */
	private function addScreenShot($params, $id_episode, $primary=false){
		$url_screen = '';
		if(isset($_FILES['screenshots']['name']) || isset($params['screenshots'])){
			$this->load->library('imageshack');
			//$this->load->library('UploadFiles');
			
			$image = FALSE;
			if(isset($_FILES['screenshots']['name'])){
				if(!empty($_FILES['screenshots']['name'])){
					$image = $this->imageshack->upload(
						array(
							'file' 		=> 'screenshots',
							'img_temp' 	=> TRUE,
							'size' 		=> array('1280x0')
						));
					//$image = $this->uploadfiles->uploadFile();
				}
				
			}

			if(isset($params['screenshots']) && $image==FALSE){
				if(!empty($params['screenshots'])){
					$image = $this->imageshack->upload(
						array(
							'file' 		=> $params['screenshots'],
							'img_temp' 	=> FALSE,
							'size' 		=> array('1280x0')
						));
					//$image = $this->uploadfiles->uploadFile();
				}
			}
			
			if($image != FALSE){
				if($primary)
					$this->db->update('series_capitulos_capturas', array('primaria' => '0'), 'id_capitulo = '.$id_episode);
				
				$url_screen = $this->imageshack->getInfo('image_link', '1280x0'); //$image['1280x0']['url']
				
				$values = array(
					'id_capitulo' 	=> $id_episode,
					'url_captura' 	=> $url_screen,
					'primaria' 		=> '1'
				);
				$this->db->insert('series_capitulos_capturas', $values);
			}
		}
	}

	private function addSourcesServers($params, $id_episode){
		if(isset($params["servers"]) && isset($params['sources'])){
			if(count($params['servers']) > 0 && count($params['sources']) > 0){
				$goo = new goo();
				
				$values = array();
				foreach ($params['servers'] as $key => $itm) {
					$values[] = array(
						'id_servidor' 	=> $itm,
						'id_capitulo' 	=> $id_episode,
						'fuente' 		=> $goo->shorten($params['sources'][$key]),
						'fuente_origen'	=> $params['sources'][$key],
						'online'		=> $params['online'][$key]
					);
				}
				$this->db->insert_batch('series_capitulos_fuentes', $values);
			}
		}
	}
	
	
	
	
	/**
	 * ]]]]]]]] METODOS DE THETVDB
	 * 
	 * Busca series espesificando el nombre
	 */
	public function tvdbSearch($params){
		$tv = new TV_Shows();
		
		$data = $tv->search($params['title'].(isset($params['year'])? ' '.$params['year']: ''));
		$res = array('serie_list' => array());
		foreach ($data as $key => $value) {
			$res['serie_list'][] = array(
				'original_name' => $value->seriesName,
				'tvdb_id' 		=> $value->id,
				'imdb_id' 		=> $value->imdbId,
				'status' 		=> $value->status
			);
		}
		
		return $res;
	}
	
	/**
	 * Obtiene la informacion de una serie
	 */
	public function tvdbSerie($params){
		$this->load->model('films_model');
		
		$tv = new TV_Shows();
		
		$data = $tv->findById($params['tvdb_id']);
		
		$res = array('serie' => array());
		$res['serie'] = array(
			'original_name' => $data->seriesName,
			'tvdb_id' 		=> $data->id,
			'imdb_id' 		=> $data->imdbId,
			'status' 		=> $data->status,
			'synopsis_spa'	=> $data->overview_spa,
			'synopsis_eng'	=> $data->overview,
			'released'		=> $data->firstAired,
			'poster'		=> $data->poster,
			'cast'			=> $this->films_model->tvdbGetCast($data->actors),
			'categories'	=> $data->genres
		);
		
		return $res;
	}
	
	/**
	 * Obtiene la informacion de un episodio
	 */
	public function tvdbEpisode($params){
		$tv = new TV_Shows();
		
		$data = $tv->findById($params['tvdb_id']);
		
		$episode = $data->getEpisode($params['season'], $params['episode']);
				
		if(is_object($episode)){
			$res = array('episode' => array());
			$res['episode'] = array(
				'tvdb_episode_id'	=> $episode->id,
				'original_name' 	=> $episode->name,
				'season' 			=> $episode->season,
				'episode' 			=> $episode->episode,
				'synopsis_spa'		=> $episode->overview_spa,
				'synopsis_eng'		=> $episode->overview,
				'released'			=> $episode->firstAired,
				'imdb_id' 			=> $episode->imdbId
			);
			
			return $res;
		}
		else 
			return 1;
		
	}
	
	


	private function exist($table, $sql, $return_res=false){
		$res = $this->db->get_where($table, $sql);
		if($res->num_rows() > 0){
			if($return_res)
				return $res->row();
			return TRUE;
		}
		return FALSE;
	}
	
	
	/**
	 * Regresa las series con sus temporadas y capitulos respectivamente.
	 */
	public function getSeriesFull($params){		
				
		$sql_where_like = (isset($params['busqueda'])) ? ((!empty($params['busqueda'])) ? " WHERE s.titulo LIKE '%".$params['busqueda']."%'" : '') : '' ;
		
		$sql = "SELECT s.id_serie, (SELECT '') as id_temporada, (SELECT '') as id_capitulo, s.titulo, 'serie' as type, s.titulo as serie 
					FROM series AS s $sql_where_like";
		
		$query 		= Sys::pagination($sql, $params, TRUE);
		$res_query 	= $this->db->query($query['query']);
		$response	= array(
							'series'			=> $res_query->result_array(),
							'total_rows' 		=> $query['total_rows'],
							'items_per_page' 	=> $params['result_items_per_page'],
							'result_page' 		=> $params['result_page']
						);
		
		if(count($response['series'])>0){
			foreach ($response['series'] as $key => $itm){
				$query = $this->db->query("SELECT * FROM (
				
							(SELECT st.id_serie, st.id_temporada, (SELECT '') as id_capitulo, CONCAT('Temporada ',st.no_temporada) as titulo, 'temporada' as type, s.titulo as serie, st.no_temporada as num, '' as status
								FROM series_temporadas as st
									INNER JOIN series as s ON st.id_serie = s.id_serie
								WHERE st.prox_estreno != 1
							)
							
							UNION
							
							(SELECT st.id_serie, st.id_temporada, sc.id_capitulo, CONCAT('Episodio ', sc.no_capitulo, ' - ', sc.titulo , ' | ' , CASE sc.status WHEN 1 THEN 'Si' ELSE 'No' END) as titulo, 'episodio' as type, st.titulo as serie, sc.no_capitulo as num, sc.status
								FROM series_capitulos as sc 
									INNER JOIN (
												SELECT s.titulo, st.id_serie, st.id_temporada 
													FROM series as s 
														INNER JOIN series_temporadas as st ON s.id_serie=st.id_serie) as st 
									ON sc.id_temporada = st.id_temporada
							) 
						) as r WHERE id_serie=".$itm['id_serie']." ORDER BY num ASC");
						$response['series'][$key]['tem_epi'] = $query->result_array();
				}
		}
		return  $response;
		
	}
	
	
	
	
}
?>
